package com.yungu.swift.admin.base;

import com.yungu.swift.admin.route.helper.JwtHelper;
import com.yungu.swift.base.model.admin.AdminParam;
import com.yungu.swift.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.IOException;

/**
 * @author : cuixiuyin
 * @date : 2019/7/9
 */
@Slf4j
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 用于判定是否需要处理该参数分解，返回 true 为需要，并会去调用下面的方法resolveArgument。
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(AdminParam.class)
                && methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 真正用于处理参数分解的方法，返回的 Object 就是controller方法上的形参对象。
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String accessToken = nativeWebRequest.getHeader(GatewayHeader.accessToken);
        try {
            AdminParam adminParam = JsonUtils.readValue(JwtHelper.parseJWT(accessToken), AdminParam.class);
            return adminParam;
        } catch (IOException e) {
            log.error("CurrentUserHandlerMethodArgumentResolver resolveArgument readValue error.accessToken:{}", accessToken, e);
        } catch (Exception e) {
            log.error("CurrentUserHandlerMethodArgumentResolver resolveArgument error.accessToken:{}", accessToken, e);
        }
        return null;
    }
}
